// 获取相关元素
const menuPopup = document.getElementById('menuPopup');
const area = document.getElementById('Area');
const changeNicknameBtnPopup = document.getElementById('change-nickname-btn-popup');
const nicknamePopupContainer = document.getElementById('nickname-popup-container');
const cancelBtn = document.getElementById('cancel-btn');
const saveBtn = document.getElementById('save-btn');
const nicknameInput = document.getElementById('nickname-input');
const nicknameLength = document.getElementById('nickname-length');
const exitBtn = document.getElementById('exitBtn');
const exitPopup = document.getElementById('exitPopup');
const cancelExitBtn = document.getElementById('cancelExitBtn');
const confirmExitBtn = document.getElementById('confirmExitBtn');
const inviteModal = document.getElementById('inviteModal');
const closeBtn = document.getElementsByClassName('close')[0];
const memberList = document.getElementById('member-list');

// 显示菜单弹窗函数
function toggleMenu(event) {
    if (menuPopup.style.display === 'block') {
        menuPopup.style.display = 'none';
    } else {
        menuPopup.style.display = 'block';
        const areaRect = area.getBoundingClientRect();
        menuPopup.style.left = areaRect.right + 'px';
        menuPopup.style.top = areaRect.top + 'px';

        menuPopup.addEventListener('mouseleave', function () {
            menuPopup.style.display = 'none';
        });
    }
}

// 显示昵称弹窗函数
function showNicknamePopup() {
    nicknamePopupContainer.style.display = 'flex';
}

// 隐藏昵称弹窗函数
function hideNicknamePopup() {
    nicknamePopupContainer.style.display = 'none';
}

// 点击取消按钮时隐藏昵称弹窗
cancelBtn.addEventListener('click', hideNicknamePopup);

// 实时更新昵称输入长度提示
nicknameInput.addEventListener('input', function () {
    const length = nicknameInput.value.length;
    nicknameLength.textContent = `${length}/10`;
});

// 点击保存按钮时发送数据到后端
saveBtn.addEventListener('click', function () {
    const newNickname = nicknameInput.value.trim();

    // 验证昵称长度
    if (newNickname.length < 0 || newNickname.length > 10) {
        alert('昵称长度必须在0到10个字符之间');
        return;
    }

    // 构造要发送的数据
    const data = {
        rcomid: 'b80Xmw', // 替换为实际的rcomid
        nickName: newNickname
    };

    // 发送数据到后端
    fetch('https://localhost:9090/update-nickname', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                alert('昵称更新成功！');
                hideNicknamePopup();
            } else {
                alert('昵称更新失败：' + result.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('网络错误，请稍后重试');
        });
});

// 为菜单中的“我在本域的昵称”按钮添加点击事件
if (changeNicknameBtnPopup) {
    changeNicknameBtnPopup.addEventListener('click', showNicknamePopup);
}

// 点击“xxx的域”旁边的三个点，弹出和隐藏菜单
area.addEventListener('click', toggleMenu);

// 聊天功能相关的JavaScript代码
document.getElementById('send-button').addEventListener('click', function () {
    const input = document.getElementById('chat-input');
    const message = input.value;
    if (message.trim() !== '') {
        const li = document.createElement('li');
        li.innerHTML = '<span>你' + new Date().toLocaleString() + '</span><p>' + message + '</p>';
        document.getElementById('chat-messages').appendChild(li);
        input.value = '';
        // 滚动到最新消息
        const chatMessages = document.getElementById('chat-messages');
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
});

// 获取聊天室成员列表并显示
function fetchAndDisplayMembers() {
    const roomId = 'your-room-id'; // 替换为实际的roomId
    fetch(`/room/getList/${roomId}`, {
        method: 'GET',
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空现有成员列表
                memberList.innerHTML = '';

                // 添加在线成员
                const onlineMembers = data.onlineMembers || [];
                onlineMembers.forEach(member => {
                    const li = document.createElement('li');
                    li.innerHTML = `
                    <span class="status-online">在线</span>
                    <span>${member.name}</span>
                `;
                    memberList.appendChild(li);
                });

                // 添加离线成员
                const offlineMembers = data.offlineMembers || [];
                offlineMembers.forEach(member => {
                    const li = document.createElement('li');
                    li.innerHTML = `
                    <span class="status-offline">离线</span>
                    <span>${member.name}</span>
                `;
                    memberList.appendChild(li);
                });
            } else {
                alert('获取成员列表失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('网络错误，请稍后重试');
        });
}

// 页面加载时获取成员列表
window.addEventListener('load', fetchAndDisplayMembers);

// 成员列表搜索功能相关的JavaScript代码
document.getElementById('search-button').addEventListener('click', function () {
    const searchInput = document.getElementById('search-input');
    const searchValue = searchInput.value.toLowerCase();
    const members = memberList.getElementsByTagName('li');

    for (let i = 0; i < members.length; i++) {
        const member = members[i];
        const memberText = member.innerText.toLowerCase();
        if (memberText.includes(searchValue)) {
            member.style.display = 'flex';
        } else {
            member.style.display = 'none';
        }
    }
});

// 显示退出域弹窗
exitBtn.addEventListener('click', function () {
    exitPopup.style.display = 'flex';
});

// 点击取消退出域按钮隐藏弹窗
cancelExitBtn.addEventListener('click', function () {
    exitPopup.style.display = 'none';
});

// 点击确认退出域按钮，发送退出请求到后端
confirmExitBtn.addEventListener('click', function () {
    const roomId = 'your-room-id'; // 替换为实际的roomId
    fetch(`/room/logout/${roomId}`, {
        method: 'GET',
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                alert('退出聊天室成功！');
                // 这里可以添加页面跳转或其他逻辑
                window.location.href = '/'; // 例如跳转到首页
            } else {
                alert('退出聊天室失败：' + result.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('网络错误，请稍后重试');
        });

    exitPopup.style.display = 'none';
});

// 显示邀请弹窗
function showInviteModal() {
    inviteModal.style.display = 'block';
}

// 当用户点击关闭按钮时，关闭邀请弹窗
closeBtn.onclick = function () {
    inviteModal.style.display = "none";
};

// 当用户点击弹窗外部时，关闭邀请弹窗
window.onclick = function (event) {
    if (event.target == inviteModal) {
        inviteModal.style.display = "none";
    }
};

// 复制链接到剪贴板的函数
function copyLink() {
    var inviteLink = document.getElementById('inviteLink');
    inviteLink.select();
    inviteLink.setSelectionRange(0, 99999);
    document.execCommand('copy');
    alert('邀请链接已复制到剪贴板！');
}